import { previewList } from './../modules/galleryPreview'
import { getGalleryThumb } from './../../service/getData'
import galleryPreviewActions from './../actions/galleryPreviewActions'
let imgPatt = /<img[^>]+src=['"]([^'"]+)['"]+/

export default {
  async preLoadThumb ({ commit, state }, {index, action}) {
    if (index < 1 || index > previewList.state.pageLength) {
      return
    }
    if (index === previewList.state.data[previewList.state.data.length - 1].page && action === 'NEXT') {
      await galleryPreviewActions.previewLoadMore({ commit, state: previewList.state })
    }
    if (index === previewList.state.data[0].page && action === 'PREVIOUS') {
      await galleryPreviewActions.previewLoadTop({ commit, state: previewList.state })
    }
    var Sthumb = previewList.state.data.filter(function (element) {
      return element.page === index
    })
    if (state.thumbList[index - 1].state === 'pending') {
      state.thumbList[index - 1].state = 'loading'
      let thumbData = await getGalleryThumb(state.gid, Sthumb[0].imgKey, Sthumb[0].page, state.showKey)
      let image = new Image()
      let imgSrc = thumbData.i3.match(imgPatt)[1]
      image.src = imgSrc
      image.onload = function (e) {
        state.thumbList[index - 1].src = imgSrc
        state.thumbList[index - 1].state = 'finished'
      }
    }
  }
}
